<template>
  <div class="dnssec-single-page">
    <div class="dnssec-container">
            <!-- Page Header -->
            <div class="page-header">
              <h1 class="page-title">DNSSEC 验证</h1>
              <p class="page-subtitle">验证递归服务器 检测权威侧的DNSSEC配置错误 的能力</p>
            </div>

            <!-- Search Card -->
            <div class="search-card">
              <div class="search-input-group">
                <label class="input-label">IP 地址</label>
                <div class="input-wrapper">
                  <input
                    v-model="ipRange"
                    type="text"
                    class="modern-input"
                    placeholder="例：192.168.1.0"
                    :disabled="isScanning"
                  >
                </div>
              </div>
              <div class="search-actions">
                <button 
                  class="action-button primary"
                  @click="startScan"
                  :disabled="isScanning"
                >
                  <span class="button-icon" v-if="isScanning">
                    <i class="el-icon-loading"></i>
                  </span>
                  <span v-else>
                    开始验证
                  </span>
                </button>
                <button 
                  class="action-button secondary"
                  @click="clearLogs"
                  :disabled="isScanning"
                >
                  清除日志
                </button>

                (提示:如果配置错误是1类型，服务器返回错误1类型，说明检测出正确的错误；如果服务器返回2，3等其他错误类型，说明检测出错误；如果没有返回错误，说明没有检测出错误)
              </div>
            </div>

            <!-- Results Area -->
            <div class="results-area" v-if="logEntries.length > 0">
              <div class="results-header">
                <h2 class="section-title">验证结果</h2>
                <span class="results-count">{{ logEntries.length }} 条记录</span>
              </div>

              <!-- Results List -->
              <div class="results-list">
                <div 
                  v-for="(log, index) in logEntries" 
                  :key="index"
                  class="result-card"
                  :class="[log.status]"
                >
                  <!-- Card Header -->
                  <div class="result-card-header">
                    <div class="status-badge" :class="log.status">
                      {{ log.status === 'safe' ? '验证成功' : '验证失败' }}
                    </div>
                    <span class="timestamp">{{ log.time }}</span>
                    <span class="ip-address">{{ log.ip }}</span>
                  </div>

                  <!-- Basic Info -->
                  <div class="info-section">
                    <h3 class="section-subtitle">基本信息</h3>
                    <div class="info-grid">
                      <div 
                        v-for="(item, idx) in log.message.basicInfo"
                        :key="'basic-'+idx"
                        class="info-item"
                      >
                        <span class="info-label">{{ item.label }}</span>
                        <span :class="['info-value', item.value.includes('成功') ? 'success' : item.value.includes('失败') ? 'error' : '']">
                          {{ item.value }}
                        </span>
                      </div>
                    </div>
                  </div>

                  <!-- Error Details -->
                  <div class="error-section">
                    <h3 class="section-subtitle">
                      <span class="subtitle-icon">⚠️</span>
                      错误类型检测
                    </h3>
                    <div class="error-grid">
                      <div 
                        v-for="(error, idx) in log.message.errorDetails"
                        :key="'error-'+idx"
                        class="error-item"
                      >
                        <span class="error-label">{{ error.label }}</span>
                        <span :class="[
                          'error-value',
                          error.value === 0 ? 'status-danger' :
                          error.value === 1 ? 'status-warning' :
                          'status-safe'
                        ]">
                          {{ error.value === 0 ? '没有检测出错误' :
                             error.value === 1 ? '检测出错误' :
                             '检测出正确的错误' }}
                        </span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- Empty State -->
            <div v-else class="empty-state">
              <div class="empty-icon">🔍</div>
              <h3 class="empty-title">暂无验证记录</h3>
              <p class="empty-description">输入 IP 地址并点击"开始验证"开始 DNSSEC 验证</p>
            </div>
    </div>
  </div>
</template>

<script setup>

import { ref } from 'vue'
import axios from 'axios'

// API Endpoint
const API_ENDPOINT = 'http://8.163.29.103:9000/dnssec/single'

// Reactive State
const ipRange = ref('')
const logEntries = ref([])
const isScanning = ref(false)
const startScan = async () => {
  try {
    isScanning.value = true
    // clearLogs()
    // 打印请求参数
    console.log('请求参数:', {
      ip: ipRange.value,
      timestamp: new Date().toISOString()
    });
    const startTime = Date.now() // 记录开始时间
    const response = await axios.get(API_ENDPOINT, {
      params: { ip: ipRange.value }, // 参数放在这里
      // headers: { 'Content-Type': 'application/json' }
    }, {
      headers: {
        'Content-Type': 'application/json',
      }
    })
    const responseTime = Date.now() - startTime // 计算耗时
    console.log('返回数据：', response.data)
    if (response.data.code === 200) {
      // 处理响应数据，支持单个对象和数组两种格式
      const resultData = Array.isArray(response.data.data) ? response.data.data[0] : response.data.data;
      if (resultData) {
        updateScanResults(resultData, responseTime);
      } else {
        handleError(new Error('No valid data received'));
      }
    }
  } catch (error) {
    handleError(error)
  } finally {
    isScanning.value = false
  }
}
// 清理旧日志
// 清除日志方法
const clearLogs = () => {
  logEntries.value = []  // 清空日志数组
  scanResults.value.errorTypes = {  // 重置错误统计
    'Unsupported DS': 0,
    'Unsupported DNSKEY': 0,
    'Invalid Signature': 0,
    'Expired Signature': 0,
    'DNSKEY Missing': 0,
    'NSEC Missing': 0,
    'RRSIG Missing': 0,
    'Zone Key Absent': 0
  }
}
// const clearLogs = () => {
//   logEntries.value = []
//   scanResults.value.errorTypes = {
//     'RRSIG Missing': 0,
//     'Unsupported DNSKEY': 0,
//     'Expired Signature': 0,
//     'Algorithm Not Supported': 0
//   }
// }
// 轮询任务进度
// 修改轮询逻辑
// const pollScanProgress = (taskId) => {
//   const interval = setInterval(async () => {
//     try {
//       const res = await axios.get(`${API_ENDPOINT}/progress/${taskId}`)
//
//       if (res.data.code === 200 && res.data.data) {
//         // 直接处理最终结果（假设单次探测无中间状态）
//         clearInterval(interval)
//         updateScanResults(res.data.data)
//       }
//     } catch (err) {
//       clearInterval(interval)
//       handleError(err)
//     }
//   }, 3000)
// }

// 更新扫描结果
const updateScanResults = (resultData,responseTime) => {
  const formattedData = formatDNSSECResult(resultData, responseTime)
  // 生成日志条目
  logEntries.value.unshift({
    time: new Date().toLocaleTimeString(),
    ip: resultData.ip || '未知IP',
    message: formattedData,
    status: resultData.is_dnssec_verified ? 'safe' : 'danger'
  })

}
// 数据结构转换器
const formatDNSSECResult = (data, responseTime) => {
  return {
    basicInfo: [
      { label: 'DNSSEC支持', value: data.is_dnssec_support ? '已支持' : '未支持', type: 'status' },
      { label: '验证状态', value: data.is_dnssec_verified ? '验证成功' : '验证失败', type: 'status' },
      { label: '响应时间', value: `${responseTime}ms`, type: 'info' } // 需确保有 responseTime 参数传入
    ],
    errorDetails: [
      { label: 'unsupportedDs', value: data.unsupportedDs, type: 'error' },
      { label: 'unsupportedDnskey', value: data.unsupportedDnskey, type: 'error' },
      { label: 'signatureNotValid', value: data.signatureNotValid, type: 'error' },
      { label: 'signatureExpired', value: data.signatureExpired, type: 'error' },
      { label: 'dnskeyMissing', value: data.dnskeyMissing, type: 'error' },
      { label: 'nsecMissing', value: data.nsecMissing, type: 'error' },
      { label: 'rrsigMissing', value: data.rrsigMissing, type: 'error' },
      { label: 'noZoneKey', value: data.noZoneKey, type: 'error' }
    ]
  }
}

// 错误处理
const handleError = (error) => {
  console.error('请求失败:', error)
  logEntries.value.push({
    time: new Date().toLocaleTimeString(),
    message: `探测失败: ${error.message}`,
    status: 'danger'
  })
}


</script>

<style scoped>
/* Base Styles */
.dnssec-container {
  padding: 2rem;
  width: 100%;
  min-height: calc(100vh - 64px);
  background: #ffffff;
  border-radius: 16px;
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.05);
}

/* Page Header */
.page-header {
  text-align: center;
  margin-bottom: 3rem;
  max-width: 1400px;
  margin-left: auto;
  margin-right: auto;
}

.page-title {
  font-size: 2rem;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0 0 0.5rem;
}

.page-subtitle {
  font-size: 1rem;
  color: #666;
  margin: 0;
}

/* Search Card */
.search-card {
  background: #f8fafc;
  border-radius: 12px;
  padding: 2rem;
  margin-bottom: 2rem;
  max-width: 1600px;
  margin-left: auto;
  margin-right: auto;
}

.search-input-group {
  margin-bottom: 1.5rem;
}

.input-label {
  display: block;
  font-weight: 500;
  color: #1a1a1a;
  margin-bottom: 0.5rem;
}

.input-wrapper {
  position: relative;
}

.modern-input {
  width: 100%;
  padding: 0.75rem 1rem;
  font-size: 1rem;
  border: 2px solid #e5e7eb;
  border-radius: 8px;
  transition: all 0.2s;
}

.modern-input:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.modern-input:disabled {
  background: #f3f4f6;
  cursor: not-allowed;
}

.search-actions {
  display: flex;
  gap: 1rem;
  justify-content: flex-start;
}

/* Layout */
.common-layout {
  min-height: 100vh;
  display: flex;
}

:deep(.el-container) {
  min-height: 100vh;
  width: 100%;
}

:deep(.el-main) {
  padding: 32px;
  background: #f6f8fc;
  display: flex;
  justify-content: center;
  align-items: flex-start;
}

/* Buttons */
.action-button {
  padding: 0.75rem 1.5rem;
  font-size: 1rem;
  font-weight: 500;
  border-radius: 8px;
  border: none;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.action-button.primary {
  background: #3b82f6;
  color: white;
}

.action-button.primary:hover {
  background: #2563eb;
}

.action-button.secondary {
  background: #fff;
  border: 2px solid #e5e7eb;
  color: #4b5563;
}

.action-button.secondary:hover {
  background: #f9fafb;
  border-color: #d1d5db;
}

.action-button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* Results Area */
.results-area {
  margin-top: 2rem;
  max-width: 1400px;
  margin-left: auto;
  margin-right: auto;
}

.results-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 1.5rem;
}

.section-title {
  font-size: 1.25rem;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0;
}

.results-count {
  font-size: 0.875rem;
  color: #6b7280;
  background: #f3f4f6;
  padding: 0.25rem 0.75rem;
  border-radius: 9999px;
}

/* Result Cards */
.result-card {
  background: #fff;
  border-radius: 12px;
  border: 1px solid #e5e7eb;
  margin-bottom: 1rem;
  overflow: hidden;
  transition: all 0.2s ease;
}

.result-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.result-card.safe {
  border-left: 4px solid #10b981;
}

.result-card.danger {
  border-left: 4px solid #ef4444;
}

.result-card-header {
  display: flex;
  align-items: center;
  padding: 1rem;
  background: #f8fafc;
  border-bottom: 1px solid #e5e7eb;
  gap: 1rem;
}

.status-badge {
  padding: 0.25rem 0.75rem;
  border-radius: 9999px;
  font-size: 0.875rem;
  font-weight: 500;
}

.status-badge.safe {
  background: #dcfce7;
  color: #059669;
}

.status-badge.danger {
  background: #fee2e2;
  color: #dc2626;
}

.timestamp {
  color: #6b7280;
  font-size: 0.875rem;
}

.ip-address {
  margin-left: auto;
  background: #f3f4f6;
  padding: 0.25rem 0.75rem;
  border-radius: 6px;
  font-size: 0.875rem;
  color: #4b5563;
}

/* Info Section */
.info-section,
.error-section {
  padding: 1rem;
  border-bottom: 1px solid #e5e7eb;
}

.section-subtitle {
  font-size: 1rem;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0 0 1rem;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.info-grid,
.error-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 1.5rem;
  max-width: 1400px;
  margin-left: auto;
  margin-right: auto;
}

.info-item,
.error-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.75rem;
  background: #f8fafc;
  border-radius: 8px;
  transition: all 0.2s ease;
}

.info-item:hover,
.error-item:hover {
  background: #f0f7ff;
}

.info-label,
.error-label {
  color: #4b5563;
  font-weight: 500;
}

.info-value,
.error-value {
  font-weight: 500;
}

.info-value.success {
  color: #10b981;
}

.info-value.error {
  color: #ef4444;
}

.status-safe {
  color: #10b981;
  background: #dcfce7;
  padding: 0.25rem 0.75rem;
  border-radius: 6px;
}

.status-danger {
  color: #dc2626;
  background: #fee2e2;
  padding: 0.25rem 0.75rem;
  border-radius: 6px;
}

.status-warning {
  color: #d97706;
  background: #fef3c7;
  padding: 0.25rem 0.75rem;
  border-radius: 6px;
}

/* Empty State */
.empty-state {
  text-align: center;
  padding: 4rem 2rem;
  background: #f8fafc;
  border-radius: 12px;
  margin-top: 2rem;
}

.empty-icon {
  font-size: 3rem;
  margin-bottom: 1rem;
}

.empty-title {
  font-size: 1.25rem;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0 0 0.5rem;
}

.empty-description {
  color: #6b7280;
  margin: 0;
}

/* Responsive Design */
@media (max-width: 768px) {
  .dnssec-container {
    padding: 1rem;
  }

  .search-card {
    padding: 1rem;
  }

  .search-actions {
    flex-direction: column;
  }

  .action-button {
    width: 100%;
  }

  .info-grid,
  .error-grid {
    grid-template-columns: 1fr;
  }

  .result-card-header {
    flex-wrap: wrap;
  }

  .ip-address {
    width: 100%;
    margin: 0.5rem 0 0;
    text-align: center;
  }
}

  .action-buttons {
    flex-direction: column;
    gap: 1rem;
  }

  .error-block {
    grid-template-columns: 1fr;
  }

  .detail-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 0.5rem;
  }


.error-count {
  background: #f0f0f0;  /* 浅灰色背景 */
  color: #434343;       /* 深灰文字 */
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 0.85em;
  border: 1px solid #d9d9d9; /* 添加浅灰色边框 */
}

.log-card {
  padding: 16px;
  border-left: 4px solid transparent;
  transition: all 0.3s ease;
}

.log-card.danger {
  border-color: var(--danger-red);
  background: linear-gradient(
      to right,
      rgba(255,76,76,0.05) 0%,
      rgba(255,76,76,0.01) 100%
  );
}

.log-card.safe {
  border-color: var(--safe-green);
  background: linear-gradient(
      to right,
      rgba(82,196,26,0.05) 0%,
      rgba(82,196,26,0.01) 100%
  );
}

.log-meta {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.status-indicator {
  display: inline-block;
  width: 12px;
  height: 12px;
  border-radius: 50%;
  margin-right: 12px;
}

.status-indicator.safe {
  background: var(--safe-green);
}

.status-indicator.danger {
  background: var(--danger-red);
}

.log-time {
  color: var(--text-gray);
  font-family: 'Courier New', monospace;
  font-size: 0.9em;
}

.ip-badge {
  margin-left: auto;
  background: #f0f2f5;
  color: #606266;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.85em;
}

.log-details {
  padding-left: 28px;
}

.detail-item {
  color: #606266;
  margin: 6px 0;
  display: flex;
  align-items: center;
}

.bullet {
  color: var(--theme-blue);
  margin-right: 8px;
  font-weight: bold;
}

/* 滚动条优化 */
.log-container {
  max-height: 500px;
  overflow-y: auto;
}

.log-container::-webkit-scrollbar {
  width: 6px;
}

.log-container::-webkit-scrollbar-thumb {
  background: rgba(0,0,0,0.2);
  border-radius: 3px;
}
</style>
